<template>
  <div class="event-mapol">
    <div class="event_map_big">
      <div class="map-tip-dialog" v-show="isShowTip && horiAzimuthAngle">
        水平方位角{{ horiAzimuthAngle || "-" }}
      </div>
      <div class="dialog_map_big" :id="mapId"></div>
    </div>
    <mapol-zoom
      :autoWidth="false"
      v-if="getInstance()?.map.map"
      :height="68"
      :width="30"
      :position="[null, null, 45, 105]"
      :customStyle="customStyle"
      :colorStyle="wordStyle"
      show
      :vertical="true"
      :mapInstance="getInstance()?.map.map"
    ></mapol-zoom>
    <MapolLayerSwitcher
      :position="[null, null, 45, 11]"
      :height="60"
      :width="80"
      :activeMode.sync="activeMode"
      :modes="modes"
      @change="switchMap"
      rulerHeight="3"
      radius="4"
      :map="getInstance()?.map"
    ></MapolLayerSwitcher>
  </div>
</template>

<script>
import CTMap from "@ct/ct_map_ol";
import eventBus from "@/utils/event-bus";
// import positionIcon from '@/assets/image/position2.png' //点标记图标
// import monitorIcon from '@/assets/image/monitor-event.png' //摄像机点标记图标
import eventMapCameraIcon from "@/assets/image/event-map-camera@2x.png"; //摄像机点标记图标
import eventMapAlarmIcon from "@/assets/image/event-map-alarm@2x.png"; //告警占标记图标
import iotIcon from "@/assets/image/linkProgress/iot@2x.png"; //物联设备点标记图标
import radarIcon from "@/assets/image/linkProgress/radar@2x.png"; //雷达设备点标记图标
import { getPolygonOperate } from "@/api/alarmEvent/mapHome.js";
import { getXjxlFeaturesByIds } from "@/api/modules/eventManagement/eventManagement.js";
// 按需导入
import { MapolLayerSwitcher, MapolZoom } from "@ct/ct_map_ol/components"; // 地图初始化组件
import {
  eventOpenInfoWindow,
  eventCloseInfoWindow,
} from "@/components/eventManagement/common/mapUrl";
import eventInfoWindow from "@/views/pages/eventManagement/components/EventInfoWindow";
import { transCoordinate } from "@/utils/CommonCtMapOl";
import { fromLonLat } from "ol/proj";
import { ScaleLine } from "ol/control";
const infoWindowList = {};
// warningSource 1 - AI告警
// warningSource 2 - 人工上报
// warningSource 3 - 一键告警
// warningSource 8 - 物联告警
// warningSource 9 - 卫星告警
// warningSource 10 - 雷达告警
// warningSource 4 - 摄像机告警
// warningSource 11 - 第三方
// 耕地卫片执法: 4110101, 矿产卫片执法: 4110102 非农化卫片执法: 4110103 非粮化卫片执法: 4110104
export default {
  name: "eventMapolBig",
  components: {
    MapolLayerSwitcher,
    MapolZoom,
  },
  data() {
    return {
      weipianList: ["4110101", "4110102", "4110103", "4110104"],
      map: {}, // 地图实例
      // dialogMap:null, // dialog地图实例
      view: null, // 视图实例
      duration: 300, //地图动画时间 毫秒
      // iconVector:null, // icon 矢量容器
      // polygonVector:null, // 网格矢量容器
      // guidesVector:null, // 参考线矢量容器
      activeMode: "basic", // 切换地图组件默认样式
      modes: ["basic", "satellite"], // 切换地图组件列表样式
      getInstance: () => {}, // 闭包函数存放地图相关实例
      getDiaInstance: () => {}, // 闭包
      getPolygon: () => {}, // 闭包
      monitorIcon: null,
      // overlayType:{
      //   icon:this.showDialog,
      //   polygon:(value)=>{
      //     // console.log(value,'polygon')
      //   }
      // }, // 覆盖物类型标记
      positionOl: [], // 告警点墨卡托投影
      deivcecMonitorOl: [], // 摄像机点墨卡托投影
      // textAreaOverlay:null, // 图斑自定义文本标记
      // diaTextAreaOverlay:null,
      customStyle: {
        color: "#172537",
      },
      wordStyle: {
        "font-size": "14px",
        color: "#172537",
      },
    };
  },
  watch: {
    "orderData.warningOrderId": {
      handler(val, oldVal) {
        this.$nextTick(async () => {
          console.log(this.position, this.positionMonitor, "经纬度");
          this.positionOl = CTMap.extend.formatLayer.transCoordinate(
            this.position
          );
          if (
            Array.isArray(this.positionMonitor) &&
            this.positionMonitor.length
          ) {
            this.deivcecMonitorOl = CTMap.extend.formatLayer.transCoordinate(
              this.positionMonitor
            );
          } else {
            this.deivcecMonitorOl = [];
          }
          if (this.orderData.warningSource === "9") {
            this.deivcecMonitorOl = this.orderData.satelliteDeviceList?.length
              ? CTMap.extend.formatLayer.transCoordinate([
                  +this.orderData.satelliteDeviceList[0].longitude,
                  +this.orderData.satelliteDeviceList[0].latitude,
                ])
              : [];
            if (this.weipianList.includes(this.orderData.warningTypeId)) {
              // 四个卫片执法
              this.getXjxlFeatures();
            }
          }
          if (this.orderData.warningSource === "2") {
            // 如果是人工上报告警，则没有摄像机信息
            this.deivcecMonitorOl = [];
          }
          if (this.warningSource === "8") {
            this.monitorIcon = iotIcon;
          } else if (this.warningSource === "10") {
            this.monitorIcon = radarIcon;
          } else {
            this.monitorIcon = eventMapCameraIcon;
          }
          if (this.gridId && !this.isLocation()) {
            await this.getGdList(this.gridId);
          } else {
            this.getInstance().polygonVector.clear();
          }
          // 处理缩略图
          this.handlerSmallImgOnMap();
          this.setMarker(this.position);
          if (
            Array.isArray(this.orderData.polygonOperate) &&
            this.orderData.polygonOperate?.length
          ) {
            this.handleType(this.orderData.polygonOperate);
          }
          if (this.showLine) {
            this.$nextTick(() => {
              this.setGuides();
            });
          } else {
            if (this.getInstance()?.guidesVector) {
              this.getInstance().guidesVector.clear();
            }
          }
          if (this.getInstance()?.textAreaOverlay) {
            this.getInstance().textAreaOverlay.setPosition(null);
          }
          if (!this.gridId)
            this.getInstance().map.map.getView().setCenter(this.positionOl);
        });
      },
      immediate: true,
    },
    showLine: {
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.setGuides();
          });
        } else {
          if (this.getInstance()?.guidesVector) {
            this.getInstance().guidesVector.clear();
          }
        }
      },
      immediate: true,
    },
  },
  props: {
    isShowTip: {
      type: Boolean,
      default: false,
    },
    horiAzimuthAngle: {
      type: String | Number,
      default: "",
    },
    position: {
      type: Array,
      default: [],
    },
    positionMonitor: {
      type: Array,
      default: [],
    },
    orderData: {
      type: Object,
      default: () => {},
    },
    gridId: {
      type: String | Number,
      default: "",
    },
    taskId: {
      type: String,
      default: "",
    },
    warningSource: {
      type: String | Number,
      default: "",
    },
    mapheight: {
      type: String,
    },
    mapId: {
      type: String,
      default: "dialog_map_big",
    },
  },
  mounted() {
    this.getInstance = this.mapInit();

    eventBus.$on("changeAlarmPlace", (val) => {
      this.$nextTick(() => {
        if (!this.getInstance) {
          return;
        }
        if (this.warningSource === "8") {
          this.monitorIcon = iotIcon;
        } else if (this.warningSource === "10") {
          this.monitorIcon = radarIcon;
        } else {
          this.monitorIcon = eventMapCameraIcon;
        }
        console.log(this.getInstance, "map");
        // this.getInstance().map.map.getView().animate({center:CTMap.extend.formatLayer.transCoordinate(this.position),duration:300})
        this.setMarker(this.position);
        if (this.gridId && !this.isLocation()) {
          this.getGdList(this.gridId);
        } else {
          this.getInstance().polygonVector.clear();
        }
        this.getInstance().map.map.getView().setCenter(this.positionOl);
      });
    });
  },
  computed: {
    showLine() {
      /**
       * 逻辑：
       * 卫星告警：联动摄像机，以摄像机为中心点画参考线，连线告警点 9
       * 摄像机告警/AI告警，以摄像机为中心点画参考线，连线告警点 4 / 1
       * 物联告警：联动摄像机
       * 雷达告警：联动摄像机
       * */
      if (
        this.orderData.warningSource === "9" &&
        this.orderData.satelliteDeviceList?.length > 0
      ) {
        return true;
      }
      if (
        this.orderData.warningSource === "11" &&
        this.deivcecMonitorOl?.length > 0
      ) {
        return true;
      }
      if (
        this.orderData.warningSource === "3" &&
        this.deivcecMonitorOl?.length > 0
      ) {
        return true;
      }
      if (
        this.orderData.warningSource === "1" ||
        this.orderData.warningSource == "4"
      ) {
        return true;
      }
      if (
        this.orderData.warningSource === "8" &&
        this.orderData?.relDevice?.latitude
      ) {
        return true;
      }
      if (
        this.orderData.warningSource === "10" &&
        this.orderData?.radarDevice?.longitude
      ) {
        return true;
      }
      return false;
    },
    showMonitorIcon() {
      return this.deivcecMonitorOl.length > 0;
    },
  },
  methods: {
    // 地图初始化
    mapInit() {
      console.log("地图初始化", this.position);
      let map = new CTMap.extend.InitMap({
        domId: this.mapId,
        maxZoom: 18,
        zoom: 15,
        minZoom: 4,
        tile: "vector",
        center: CTMap.extend.formatLayer.transCoordinate(this.position),
      });
      this.view = map.map.getView();
      //创建icon矢量容器
      let iconVector = new CTMap.source.Vector();
      // 创建网格矢量容器
      let polygonVector = new CTMap.source.Vector();
      // 创建参考线矢量容器
      let guidesVector = new CTMap.source.Vector();

      //创建icon图层
      let iconLayer = new CTMap.layer.Vector({
        source: iconVector,
      });
      // 创建网格图层
      let polygonLayer = new CTMap.layer.Vector({
        source: polygonVector,
      });
      // 创建参考线图层
      let guidesLayer = new CTMap.layer.Vector({
        source: guidesVector,
      });
      // 创建overlay
      let textAreaOverlay = new CTMap.Overlay({
        positioning: "bottom-left", // 左下角
        stopEvent: false, // 拒绝阻止事件冒泡
      });
      //将图层添加到地图上
      map.map.addLayer(polygonLayer);
      map.map.addLayer(guidesLayer);
      map.map.addLayer(iconLayer);
      // 添加Overlay到地图
      map.map.addOverlay(textAreaOverlay);
      this.addScaleLine(map.map, "demarcate-scaleLine", 124);
      return () => {
        return {
          map,
          guidesVector,
          polygonVector,
          iconVector,
          textAreaOverlay,
        };
      };
    },
    handleType(data) {
      // 对不同类型处理
      data.forEach((pItme) => {
        let type = pItme.geomeryType ? pItme.geomeryType : pItme.geometryType;
        let data = {
          featureId: pItme.tbbh, // 图斑编码
          layerName: pItme.layerName, // 图层名称
        };
        if (type == "POINT") {
          // 点处理
          let geometry = CTMap.extend.formatLayer.transCoordinate(
            JSON.parse(pItme.geometry)
          );
          this.setPolygon(
            geometry,
            { color: "#FF0000" },
            data.featureId,
            true,
            type
          );
        }
        if (type == "MULTIPOINT" || type == "LINESTRING") {
          // 多点处理 //线
          // new CTMapOl.geom.lineString([[x1, y1],[x2, y2],[x3, y3],[x4, y4]])
          let geometry = JSON.parse(pItme.geometry)?.map((item) =>
            CTMap.extend.formatLayer.transCoordinate(item)
          );
          this.setPolygon(
            [geometry],
            { color: "#FF0000" },
            data.featureId,
            true,
            type
          );
        }
        if (type == "POLYGON" || type == "MULTILINESTRING") {
          // 多边形  //多线 eventid 202402221210626462338401
          let arr = JSON.parse(pItme.geometry)[0];
          let geometry = arr?.map((item) =>
            CTMap.extend.formatLayer.transCoordinate(item)
          );
          this.setPolygon(
            [geometry],
            { color: "#FF0000" },
            data.featureId,
            true,
            type
          );
        }
        if (type == "MULTIPOLYGON") {
          // 多 多边形
          let arr = JSON.parse(pItme.geometry)[0][0];
          let geometry = arr?.map((item) =>
            CTMap.extend.formatLayer.transCoordinate(item)
          );
          this.setPolygon(
            [[geometry]],
            { color: "#FF0000" },
            data.featureId,
            true,
            type
          );
        }
      });
    },
    /**
     * 设置各个告警点位逻辑集合
     * @param { Array } location 告警点经纬度
     */
    setMarker(location) {
      let coordinate = CTMap.extend.formatLayer.transCoordinate(location);
      if (this.getInstance().iconVector) {
        this.getInstance().iconVector.clear(); //每次先清空容器
      }
      let feature = [];
      if (this.orderData.warningSource === "10") {
        // 雷达告警单独处理，存在多个雷达可能，并可能存在摄像机
        //设置雷达marker
        let radarList = this.orderData?.deviceSiteList?.map((item) =>
          CTMap.extend.formatLayer.transCoordinate([
            item.longitude,
            item.latitude,
          ])
        ); // 获取雷达经纬度列表
        let raderMarkerList = radarList?.map((item) => {
          return this.setPoints(item, { src: radarIcon });
        });
        // 如果联动了摄像机，设置联动摄像机marker
        if (this.orderData?.radarDevice?.longitude) {
          let deviceLocation = CTMap.extend.formatLayer.transCoordinate([
            this.orderData.radarDevice.longitude,
            this.orderData.radarDevice.latitude,
          ]);
          let radarDevice = this.setPoints(deviceLocation, {
            src: eventMapCameraIcon,
          });
          feature.push(radarDevice);
        }
        if (raderMarkerList) {
          feature.push(...raderMarkerList);
        }
      } else if (
        this.orderData.warningSource === "9" &&
        this.orderData.satelliteDeviceList?.length
      ) {
        //  卫星告警
        if (this.orderData.satelliteDeviceList?.length) {
          let deviceLocation = CTMap.extend.formatLayer.transCoordinate([
            this.orderData.satelliteDeviceList[0].longitude,
            this.orderData.satelliteDeviceList[0].latitude,
          ]);
          let startDevice = this.setPoints(deviceLocation, {
            src: eventMapCameraIcon,
          });
          feature.push(startDevice);
          this.connectAlarmToCamera(coordinate, deviceLocation);
        }
      } else {
        //物联，摄像机，AI告警marker
        if (this.deivcecMonitorOl.length > 0) {
          feature.push(
            this.setPoints(this.deivcecMonitorOl, { src: this.monitorIcon })
          );
          this.setGuides();
        }
      }
      // 设置告警点与摄像机连线
      if (this.orderData.warningSource === "8") {
        if (this.orderData?.relDevice?.longitude) {
          // 物联告警单独处理relDevice字段为摄像机信息
          let iotDevice = CTMap.extend.formatLayer.transCoordinate([
            this.orderData?.relDevice.longitude,
            this.orderData?.relDevice.latitude,
          ]);
          feature.push(this.setPoints(iotDevice, { src: eventMapCameraIcon }));
          this.connectAlarmToCamera(coordinate, iotDevice);
        }
      } else {
        this.connectAlarmToCamera(coordinate, this.deivcecMonitorOl);
      }
      feature.push(
        this.setPoints(coordinate, {
          src: eventMapAlarmIcon,
          height: 35,
          anchor: [0.5, 1],
        })
      ); // 设置告警点
      let featureLonLat = feature.map((item) => item.values_.myCoordinate);
      let displayRange = CTMap.extent.boundingExtent(featureLonLat);
      this.getInstance().iconVector.addFeatures(feature); //将创建好的feature放入到容器中
      if (this.gridId) {
        return;
      }
      this.$nextTick(() => {
        if (featureLonLat.length === 1) {
          this.getInstance().map.map.getView().setCenter(coordinate);
          this.getInstance().map.map.getView().setZoom(6);
        } else {
          this.getInstance()
            .map.map.getView()
            .fit(displayRange, {
              padding: [30, 30, 30, 30],
            });
        }
      });
    },
    /**
     * 设置点标记样式
     * @param { Array } coordinate 坐标点位
     */
    setPoints(coordinate, iconOption) {
      if (!iconOption || !iconOption.src) {
        throw new Error("iconOption.src is required");
      }
      //创建标记feature   自定义myCoordinate属性，用于获取点标记的坐标值
      let iconFeature = new CTMap.Feature({
        type: "icon",
        geometry: new CTMap.geom.Point(coordinate),
        myCoordinate: coordinate,
      });
      let poiStyle = new CTMap.style.Style({
        image: new CTMap.style.Icon({
          width: 30,
          height: 30,
          anchor: [0.5, 0.5], // 默认值为图标中心
          ...iconOption,
        }),
      });
      iconFeature.setStyle(poiStyle);
      return iconFeature;
    },
    /**
     * 设置多边形区域
     * @param gridRange 区域坐标
     * @param color 颜色
     * @param gridName 区域名称
     * @param flag 是否为绘制图斑
     */
    setPolygon(gridRange, style, gridName, flag, type) {
      let fillColor = this.hexToRgba(
        style.color,
        style.colorTransparency || 0.5
      );
      let strokeColor = this.hexToRgba(
        style.borderColor || style.color,
        style.borderColorTransparency
      );
      let polygonStyle = new CTMap.style.Style({
        fill: new CTMap.style.Fill({
          color: fillColor,
        }),
        stroke: new CTMap.style.Stroke({
          color: strokeColor,
          width: style.borderWidth || 2,
        }),
        image: new CTMap.style.Circle({
          radius: 5,
          stroke: new CTMap.style.Stroke({
            color: strokeColor,
            width: style.borderWidth || 2,
          }),
          fill: new CTMap.style.Fill({
            color: strokeColor,
          }),
        }),
        zIndex: 20,
      });
      if (!flag) {
        polygonStyle.setText(
          new CTMap.style.Text({
            text: gridName,
            fill: new CTMap.style.Fill({
              color: "#333",
            }),
            font: "14px PingFangSC-Regular, PingFang SC",
            textAlign: "center",
            // overflow:true
          })
        );
      } else {
        if (gridName) {
          // 兼容处理图版编码为空
          this.setCustomTextArea(gridName, gridRange, type);
        }
      }
      let polygon = "";
      let featureVV = "";
      if (type == "POINT") {
        polygon = new CTMap.geom.Point(gridRange);
        featureVV = new CTMap.Feature({
          geometry: polygon,
          type: "point",
        });
      } else if (type == "MULTIPOINT") {
        polygon = new CTMap.geom.MultiPoint(gridRange);
        featureVV = new CTMap.Feature({
          geometry: polygon,
          type: "MULTIPOINT",
        });
      } else if (type == "LINESTRING") {
        polygon = new CTMap.geom.LineString(gridRange);
        featureVV = new CTMap.Feature({
          geometry: polygon,
          type: "line",
        });
      } else if (type == "MULTILINESTRING") {
        polygon = new CTMap.geom.MultiLineString(gridRange);
        featureVV = new CTMap.Feature({
          geometry: polygon,
          type: "line",
        });
      } else if (type == "POLYGON") {
        polygon = new CTMap.geom.Polygon(gridRange);
        featureVV = new CTMap.Feature({
          geometry: polygon,
          type: "polygon",
        });
      } else if (type == "MULTIPOLYGON") {
        polygon = new CTMap.geom.MultiPolygon(gridRange); // gridRange [[[[xxx,xxx],[xxx,xxx]...]]]
        featureVV = new CTMap.Feature({
          geometry: polygon,
          type: "polygon",
        });
      } else {
        polygon = new CTMap.geom.Polygon(gridRange);
        featureVV = new CTMap.Feature({
          geometry: polygon,
          type: "polygon",
        });
      }

      featureVV.setStyle(polygonStyle);
      this.getInstance().polygonVector.addFeature(featureVV);
      return polygon;
    },
    convertArray(arr, rowSize = 2) {
      let result = [];
      let rowIndex = 0;
      for (let i = 0; i < arr.length; i++) {
        if (i % rowSize === 0) {
          result.push([]);
          rowIndex++;
        }
        result[rowIndex - 1].push(arr[i]);
      }
      return result;
    },
    /**
     * 设置图斑自定义点标记
     */
    setCustomTextArea(featureId, path, type) {
      // console.log(type, path)
      var lng, lat;
      if (type == "POINT") {
        lng = path[0];
        lat = path[1];
      } else if (type == "MULTIPOINT" || type == "LINESTRING") {
        lng = this.getCenterPoint(path[0]).lng;
        lat = this.getCenterPoint(path[0]).lat;
      } else if (type == "POLYGON" || type == "MULTILINESTRING") {
        lng = this.getCenterPoint(path[0]).lng;
        lat = this.getCenterPoint(path[0]).lat;
      } else if (type == "MULTIPOLYGON") {
        lng = this.getCenterPoint(path[0][0]).lng;
        lat = this.getCenterPoint(path[0][0]).lat;
      } else {
        lng = this.getCenterPoint(path[0]).lng;
        lat = this.getCenterPoint(path[0]).lat;
      }
      // 创建一个自定义的HTML标记
      let customMarkerCont = `
					<div style=" height: 28px;
						line-height: 28px;
						user-select: none;
						border-radius: 14px;
						color: #fff;
						padding: 0 8px;
						font-size: 14px;
                        font-weight: 600;
						position: relative;
						margin: 0 0 19px 6px;
						background: linear-gradient(121deg, #E91D18 0%, #BA261F 100%);
						box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2);">
						<div style="width: 10px;
							height: 10px;
							border-radius: 50%;
							background: #E41E19;
							position: absolute;
							right: 100%;
							top: 50%;
							transform: translate(4px, -50%);"></div>
						${featureId}
						<div style="width: 4px;
							height: 32px;
							background: #E41E19;
							position: absolute;
							right: 100%;
							top: 50%;"></div>
					</div>
				`;
      let st = transCoordinate([+lng, +lat], "EPSG:3857", "EPSG:4326");
      console.log(st);
      let infoWindow = eventOpenInfoWindow(
        this.getInstance().map.map,
        st[0],
        st[1],
        customMarkerCont,
        "customTextArea",
        0,
        0,
        featureId + "TextArea",
        "bottom-left"
      );
      infoWindowList[featureId + "TextArea"] = infoWindow;
      // this.getInstance().textAreaOverlay.setElement(customMarker)
      // this.getInstance().textAreaOverlay.setPosition([lng, lat])
    },
    /**
     * 根据网格id获取网格信息
     * @param grid 网格Id
     * */
    async getGdList(gridId) {
      this.getInstance().polygonVector.clear();
      this.getInstance().textAreaOverlay.setPosition(null);
      let gridInfo = this.orderData.gridInfo;
      let colorList = gridInfo?.color?.split(",");
      let borderWidthList = gridInfo?.borderColorLineThickness?.split(",");
      let borderColorList = gridInfo?.borderColor?.split(",");
      let borderColorTransparencyList =
        gridInfo?.borderColorTransparency?.split(",");
      let colorTransparencyList = gridInfo?.colorTransparency?.split(",");
      let grid = [];
      if (gridInfo.gridRange) {
        let gridList = JSON.parse(gridInfo.gridRange);
        for (let i = 0; i < gridList.length; i++) {
          const style = {
            color: colorList[i] || "#008FFF",
            borderColor: borderColorList[i] || colorList[i] || "#008FFF",
            borderColorTransparency: borderColorTransparencyList[i] / 1 || 0.5,
            borderWidth: borderWidthList[i] || 1,
            colorTransparency: colorTransparencyList[i] / 1 || 0.5,
          };
          let item = gridList[i].map((item) =>
            CTMap.extend.formatLayer.transCoordinate(item)
          );
          grid.push(this.setPolygon([item], style, gridInfo.gridName));
        }
        let allCoordinates = gridList.flat(Infinity);
        this.getPolygon = () => {
          return { grid, gridList: allCoordinates };
        };
        this.getInstance()
          .map.map.getView()
          .fit(this.calculateBounds(allCoordinates), {
            // size:[100,100], // 图形大小，单位px
            padding: [20, 20, 20, 20], // 边距，单位px
          }); // 自适应缩放
      }
    },
    /**
     * 链接告警点和摄像机
     * */
    connectAlarmToCamera(position, positionMonitor) {
      console.log(positionMonitor, "positionMonitor");
      if (!positionMonitor?.length) {
        return;
      }
      let connectLine = new CTMap.Feature({
        geometry: new CTMap.geom.LineString([
          [position[0], position[1]], // 起点坐标
          [positionMonitor[0], positionMonitor[1]], // 终点坐标
        ]),
      });
      let lineStyle = new CTMap.style.Style({
        stroke: new CTMap.style.Stroke({
          color: "red",
        }),
      });
      connectLine.setStyle(lineStyle);
      this.getInstance().iconVector.addFeature(connectLine);
    },
    switchMap(e) {},
    //16进制颜色转rgba
    hexToRgba(hex, transparency) {
      const rgba = [];
      hex = hex.replace("#", "").padEnd(8, "F");
      for (let i = 0; i < hex.length; i += 2) {
        rgba.push(parseInt(hex.slice(i, i + 2), 16));
      }
      return `rgba(${rgba[0]},${rgba[1]},${rgba[2]},${transparency || 1})`;
    },
    // 获取图斑信息
    getPolygonOperate(val) {
      if (this.warningSource != "1") {
        return;
      }
      // 只有AI 告警请求图斑信息
      let param = null;
      if (
        !this.orderData.deviceCode ||
        !this.orderData.channelCode ||
        !this.orderData.presetId
      ) {
        return;
      }
      param = {
        taskId: val,
        deviceCode: this.orderData.deviceCode,
        channelCode: this.orderData.channelCode,
        presetId: this.orderData.presetId,
        tenantId: this.orderData.tenantId,
        industryCode: this.orderData.industryCode,
      };
      getPolygonOperate(param)
        .then((res) => {
          if (res.code == 200 && res.data.length) {
            // 对不同类型处理
            res.data.forEach((pItme) => {
              let type = pItme.geomeryType
                ? pItme.geomeryType
                : pItme.geometryType;
              let data = {
                featureId: pItme.tbbh, // 图斑编码
                layerName: pItme.layerName, // 图层名称
              };
              if (type == "POINT") {
                // 点处理
                let geometry = CTMap.extend.formatLayer.transCoordinate(
                  JSON.parse(pItme.geometry)
                );
                this.setPolygon(
                  geometry,
                  { color: "#FF0000" },
                  data.featureId,
                  true,
                  type
                );
              }
              if (type == "MULTIPOINT" || type == "LINESTRING") {
                // 多点处理 //线
                // new CTMapOl.geom.lineString([[x1, y1],[x2, y2],[x3, y3],[x4, y4]])
                let geometry = JSON.parse(pItme.geometry)?.map((item) =>
                  CTMap.extend.formatLayer.transCoordinate(item)
                );
                this.setPolygon(
                  [geometry],
                  { color: "#FF0000" },
                  data.featureId,
                  true,
                  type
                );
              }
              if (type == "POLYGON" || type == "MULTILINESTRING") {
                // 多边形  //多线 eventid 202402221210626462338401
                let arr = JSON.parse(pItme.geometry)[0];
                let geometry = arr?.map((item) =>
                  CTMap.extend.formatLayer.transCoordinate(item)
                );
                this.setPolygon(
                  [geometry],
                  { color: "#FF0000" },
                  data.featureId,
                  true,
                  type
                );
              }
              if (type == "MULTIPOLYGON") {
                // 多 多边形
                let arr = JSON.parse(pItme.geometry)[0][0];
                let geometry = arr?.map((item) =>
                  CTMap.extend.formatLayer.transCoordinate(item)
                );
                this.setPolygon(
                  [[geometry]],
                  { color: "#FF0000" },
                  data.featureId,
                  true,
                  type
                );
              }
            });
          }
        })
        .catch((err) => {});
    },
    /**
     * 设置参考线
     */
    setGuides() {
      this.getInstance().guidesVector.clear();
      let poi;
      if (this.orderData.warningSource === "8") {
        if (!this.orderData.relDevice?.latitude) {
          return;
        }
        let { latitude, longitude } = this.orderData.relDevice;
        poi = [longitude, latitude];
      } else if (this.orderData.warningSource === "9") {
        if (this.orderData.satelliteDeviceList?.length) {
          poi = [
            +this.orderData.satelliteDeviceList[0].longitude,
            +this.orderData.satelliteDeviceList[0].latitude,
          ];
        }
      } else {
        poi = CTMap.extend.formatLayer.transCooordinateFromOpenlayer(
          this.deivcecMonitorOl
        );
      }
      const [lng, lat] = poi;
      const hLine = [
        [-180, lat],
        [180, lat],
      ];
      const vLine = [
        [lng, -90],
        [lng, 90],
      ];
      const crossLine = new CTMap.Feature(
        new CTMap.geom.MultiLineString([hLine, vLine]).transform(
          "EPSG:4326",
          "EPSG:3857"
        )
      );
      const lineStroke = new CTMap.style.Stroke({
        color: "red",
        lineCap: "butt",
        lineDash: [5, 5],
      });
      const [x, y] = fromLonLat([lng, lat]);
      crossLine.setStyle(
        new CTMap.style.Style({
          stroke: lineStroke,
          // geometry: _ => {
          // 	const [minX, minY, maxX, maxY] = this.getInstance().map.map.getView().calculateExtent()
          // 	const hLine = [[minX, y], [maxX, y]]
          // 	const vLine = [[x, minY], [x, maxY]]
          // 	return new CTMap.geom.MultiLineString([hLine, vLine])
          // }
          geometry: (_) => {
            const [minX, minY, maxX, maxY] = this.getInstance()
              .map.map.getView()
              .calculateExtent();
            const leftLine = [
              [x, y],
              [minX, y],
            ];
            const rightLine = [
              [x, y],
              [maxX, y],
            ];
            const upLine = [
              [x, y],
              [x, maxY],
            ];
            const downLine = [
              [x, y],
              [x, minY],
            ];
            return new CTMap.geom.MultiLineString([
              leftLine,
              rightLine,
              upLine,
              downLine,
            ]);
          },
        })
      );
      let e = document.querySelector(".content_event_right");
      console.log(e?.clientWidth);
      let gPoint1 = new CTMap.Feature({
        geometry: new CTMap.geom.Point(
          transCoordinate(poi, "EPSG:4326", "EPSG:3857")
        ),
      });
      let poiStyle1 = new CTMap.style.Style({
        text: new CTMap.style.Text({
          text: "E",
          fill: new CTMap.style.Fill({
            color: "#FF6A6C",
          }),
          font: "bold 12px PingFangSC, PingFang SC",
          textAlign: "right",
          offsetX: e?.clientWidth / 2 - 12 || 300,
          offsetY: -12,
        }),
      });
      let gPoint2 = new CTMap.Feature({
        geometry: new CTMap.geom.Point(
          transCoordinate(poi, "EPSG:4326", "EPSG:3857")
        ),
      });
      let poiStyle2 = new CTMap.style.Style({
        text: new CTMap.style.Text({
          text: "W",
          fill: new CTMap.style.Fill({
            color: "#FF6A6C",
          }),
          font: "12px PingFangSC-Regular, PingFang SC",
          textAlign: "right",
          offsetX: -(e?.clientWidth / 2 - 24) || -300,
          offsetY: -12,
        }),
      });
      let gPoint3 = new CTMap.Feature({
        geometry: new CTMap.geom.Point(
          transCoordinate(poi, "EPSG:4326", "EPSG:3857")
        ),
      });
      let poiStyle3 = new CTMap.style.Style({
        text: new CTMap.style.Text({
          text: "S",
          fill: new CTMap.style.Fill({
            color: "#FF6A6C",
          }),
          font: "12px PingFangSC-Regular, PingFang SC",
          textAlign: "right",
          offsetX: 12,
          offsetY: e?.clientHeight / 2 - 12 || 300,
        }),
      });
      let gPoint4 = new CTMap.Feature({
        geometry: new CTMap.geom.Point(
          transCoordinate(poi, "EPSG:4326", "EPSG:3857")
        ),
      });
      let poiStyle4 = new CTMap.style.Style({
        text: new CTMap.style.Text({
          text: "N",
          fill: new CTMap.style.Fill({
            color: "#FF6A6C",
          }),
          font: "12px PingFangSC-Regular, PingFang SC",
          textAlign: "right",
          offsetX: 12,
          offsetY: -(e?.clientHeight / 2 - 12) || -300,
        }),
      });

      gPoint1.setStyle(poiStyle1);
      gPoint2.setStyle(poiStyle2);
      gPoint3.setStyle(poiStyle3);
      gPoint4.setStyle(poiStyle4);
      // referenceLineX.setStyle(lineStyle)
      // referenceLineY.setStyle(lineStyle)
      this.getInstance().guidesVector.addFeatures([
        crossLine,
        gPoint1,
        gPoint2,
        gPoint3,
        gPoint4,
      ]);
    },
    // 工具函数，判断是否是空数组
    isNullArray(val) {
      if (!Array.isArray(val)) {
        return false;
      }
      if (val.length === 0) {
        return false;
      } else {
        return true;
      }
      return false;
    },
    /**
     * 地点坐标计算中心点
     * @return { Object } {lat lng}
     * @param pointArray
     */
    getCenterPoint(pointArray) {
      let sortedLongitudeArray = pointArray.map((item) => item[0]).sort(); //首先对经度进行排序，红色部分是array中经度的名称
      let sortedLatitudeArray = pointArray.map((item) => item[1]).sort(); //对纬度进行排序，红色部分是array中纬度的名称
      let centerLongitude = (
        (parseFloat(sortedLongitudeArray[0]) +
          parseFloat(sortedLongitudeArray[sortedLongitudeArray.length - 1])) /
        2
      ).toFixed(4);
      const centerLatitude = (
        (parseFloat(sortedLatitudeArray[0]) +
          parseFloat(sortedLatitudeArray[sortedLatitudeArray.length - 1])) /
        2
      ).toFixed(4);

      return { lng: centerLongitude, lat: centerLatitude };
    },
    /**
     * 计算电子围栏的经纬度最大值最小值
     * @param coordinates 电子围栏
     * @return {(number|number)[]} 经纬度最大值最小值
     */
    calculateBounds(coordinates, flag) {
      let minLat = Infinity;
      let maxLat = -Infinity;
      let minLng = Infinity;
      let maxLng = -Infinity;
      let coordinates_ = this.convertArray(coordinates);
      coordinates_.forEach((coordinate) => {
        let lat, lng;
        if (flag) {
          [lat, lng] = coordinate;
        } else {
          [lat, lng] = CTMap.extend.formatLayer.transCoordinate(coordinate);
        }
        minLat = Math.min(minLat, lat);
        maxLat = Math.max(maxLat, lat);
        minLng = Math.min(minLng, lng);
        maxLng = Math.max(maxLng, lng);
      });

      return [minLat, minLng, maxLat, maxLng];
    },
    // 是否是属地告警
    isLocation() {
      return (
        location.href.includes("eventQueryDetail") ||
        location.href.includes("eventLocalDetail")
      );
    },
    handlerSmallImgOnMap() {
      // 先清除图片信息 1.卸载组件 2.关闭弹窗
      this.clearSmallImg();
      // 图片信息
      if (this.orderData.files?.length) {
        let smallGroup = {};
        this.orderData.files.forEach((item) => {
          // 数据先分组
          if (smallGroup[item.latitude + "_" + item.longitude]) {
            smallGroup[item.latitude + "_" + item.longitude].push(item);
          } else {
            smallGroup[item.latitude + "_" + item.longitude] = [item];
          }
        });
        // console.log(smallGroup)
        Object.keys(smallGroup).forEach((key) => {
          // console.log('key', key)
          smallGroup[key].forEach((smallGroupItem, index) => {
            // console.log('smallGroupItem', smallGroupItem)
            let imgArr = smallGroupItem.orderFiles.filter(
              (fItem) => fItem.resourceType == "1"
            );
            // console.log(imgArr)
            if (imgArr.length && index == 0) {
              // 有图片才渲染且只渲染第一条
              this.setSmallImgInfo(smallGroup[key]);
            }
          });
        });
      }
    },
    setSmallImgInfo(smallGroupArr) {
      let smallImgInfo = smallGroupArr[0];
      // let fileWaterMark = JSON.parse(smallImgInfo.fileWaterMark)
      let id = "event_" + smallImgInfo.longitude + "_" + smallImgInfo.latitude;
      let lng = +smallImgInfo.longitude;
      let lat = +smallImgInfo.latitude;
      let content = `<div class="eventInfoWinVC" id="${id}"></div>`;
      // map, lng, lat, content, popClass, offsetX, offsetY, infoWindowId
      let infoWindow = eventOpenInfoWindow(
        this.getInstance().map.map,
        lng,
        lat,
        content,
        "event_vue_comp_map",
        0,
        0,
        id
      );
      infoWindowList[id] = infoWindow;
      // 调用扩展组件
      eventInfoWindow.show({ orderData: smallGroupArr });
      console.log("infoWindowList", infoWindowList);
    },
    clearSmallImg() {
      eventInfoWindow.close();
      Object.keys(infoWindowList).forEach((key) => {
        eventCloseInfoWindow(this.getInstance().map.map, infoWindowList[key]);
        delete infoWindowList[key];
      });
    },
    getXjxlFeatures() {
      let params = {
        layerID: this.orderData.spot?.layerId,
        bsm: this.orderData.spot?.bsm,
        returnAllCols: true,
        returnGeometry: true,
      };
      getXjxlFeaturesByIds(params).then((res) => {
        if (res.code == "200") {
          let geoData = res.data.geoData;
          let coordinates = geoData.features[0].geometry.coordinates;
          let geoType = geoData.features[0].geometry.type;
          let coordinates_ = this.formatGeometry({
            coordinates,
            type: geoType,
          });
          this.setPolygon(
            coordinates_,
            { color: "#4F9FFF" },
            "",
            true,
            res.data.geoType
          );

          setTimeout(() => {
            let allCoordinates = coordinates_.flat(Infinity);
            let resCound = this.calculateBounds(allCoordinates, true);
            this.getInstance()
              .map.map.getView()
              .fit(resCound, {
                padding: [20, 20, 20, 20], // 边距，单位px
              }); // 自适应缩放
          }, 500);
        }
      });
    },

    formatGeometry(data) {
      const { coordinates, type } = data || {};
      let geometry = "";
      if (type == "Point" || type == "MultiPoint") {
        geometry = CTMap.extend.formatLayer.transCoordinate(coordinates);
        return geometry;
      } else if (type == "MultiLineString" || type == "LineString") {
        geometry = CTMap.extend.formatLayer.transCoordinate(coordinates[0]);
        return [geometry];
      } else if (type == "MultiPolygon" || type == "Polygon") {
        geometry = coordinates[0][0].map((item) =>
          CTMap.extend.formatLayer.transCoordinate(item)
        );
        return [[geometry]];
      }
    },
    addScaleLine(map, className, maxWidth, divId) {
      let option = {
        className: className,
        units: "metric",
      };
      if (maxWidth) {
        option.maxWidth = maxWidth;
      }
      if (divId) {
        option.target = document.getElementById(divId);
      }
      let scaleLine = new ScaleLine(option);
      map.addControl(scaleLine);
      return scaleLine;
    },
  },
  beforeDestroy() {
    this.getInstance = null; // 清除闭包，防止内存泄露
    this.getDiaInstance = null;
  },
};
</script>

<style scoped lang="scss">
.event-mapol {
  width: 100%;
  height: 100%;
  position: relative;

  .event_map_big {
    height: 100%;
  }
}

.map-tip {
  position: absolute;
  top: 9px;
  right: 10px;
  line-height: 200%;
  font-size: 10px;
  background: rgba(147, 147, 147, 0.7);
  color: white;
  padding: 2px 5px;
  border-radius: 5px;
}

/deep/.ol-zoom,
/deep/.ol-rotate {
  display: none;
}

.map-tip-dialog {
  position: absolute;
  top: 12px;
  right: 12px;
  z-index: 99999;
  font-size: 12px;
  background: rgba(0, 0, 0, 0.4);
  color: #ffffff;
  padding: 6px 12px;
  border-radius: 2px;
  line-height: 1;
}

/deep/ .el-dialog__headerbtn {
  top: 10px !important;
  right: 10px;
}

.dialog_map_big {
  height: 100%;
  width: 100%;
  position: relative;
}
</style>
<style lang="scss">
.medias-map-component .ct-mapol-layer-switcher__container {
  padding: 4px 0 !important;
  margin-left: 4px;
  display: flex;
  justify-content: space-between;
  width: unset !important;
}

.dialog_map_big {
  .ol-viewport {
    border-radius: 6px;
  }
  .demarcate-scaleLine {
    position: absolute;
    left: 11px;
    bottom: 15px;
    background: #ffffff;
    box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.15);
    border-radius: 4px;
    padding: 0 10px;
    &:before {
      content: "";
      width: 2px;
      height: 6px;
      pointer-events: none;
      position: absolute;
      left: 9px;
      top: 3px;
      background: #172537;
    }
    &:after {
      content: "";
      width: 2px;
      height: 6px;
      pointer-events: none;
      position: absolute;
      right: 9px;
      top: 3px;
      background: #172537;
    }
    .demarcate-scaleLine-inner {
      margin-top: 5px;
      margin-bottom: 3px;
      padding-top: 2px;
      border-top: 2px solid #172537;
      color: #172537;
      font-size: 10px;
      text-align: center;
      transition: all 0.25s;
      will-change: contents, width;
    }
  }
}
</style>
